package com.Aug.service;

import com.Aug.constant.Constant;
import com.Aug.dao.UserDao;
import com.Aug.entity.User;
import com.Aug.exception.PasswordIncorrectException;
import com.Aug.exception.UserIsExistException;
import com.Aug.exception.UserIsNotExistException;
import com.Aug.util.MD5Util;

import java.util.List;


public class UserService {

    UserDao userDao = new UserDao();

    //执行业务逻辑
    public void register(User user) {
        //实质是 向数据库插入一条数据
        //设计密码
        String password = user.getName() + user.getPassword() + Constant.SALT;

        user.setPassword(MD5Util.Digest(password));

        List<User> userByname = userDao.findUserByname(user.getName());
        if (userByname.size() > 0){
            throw new UserIsExistException();
        }else {
            userDao.save(user);
        }

    }

    public Boolean checkUserName(String username) {

        List<User> users = userDao.findUserByname(username);
        return users.size() > 0;

    }

    //根据用户名获取头像
    public String getProfile(String username) {
        List<User> users = userDao.findUserByname(username);
        if(users.size() > 0 ){
            return users.get(0).getProfile();
        }
        return null;
    }

    public void login(User user) {
        List<User> users = userDao.findUserByname(user.getName());
        if(users.size() == 0 ){
            throw new UserIsNotExistException();
        }

        User realUser = users.get(0);
        //需要对密码进行加盐加密处理
        if(user.getPassword() != null && user.getName() != null){
            String password = user.getName() + user.getPassword() + Constant.SALT;
            password = MD5Util.Digest(password);
            if (!password.equals(realUser.getPassword())){
                throw new PasswordIncorrectException();
            }
        }

    }

    public List<User> findAllUsers(Integer currentPage, Integer pageSize) {
        return userDao.findAllUsers(currentPage,pageSize);
    }

    public void deleteById(String id) {
        userDao.deleteById(id);
    }

    public User findUserById(Integer id) {
        return userDao.findUserById(id);
    }

    public void update(User user) {
        userDao.update(user);
    }

    public Integer getUserTotal() {
        return userDao.getUserTotal();
    }
}
